#!/usr/bin/env python3
import tempfile
import os
import json
import shutil
import subprocess

cwd = os.getcwd()


def load_changelog():
    with open('CHANGELOG', 'r') as f:
        clog = json.load(f)
    versions = clog['versions']
    latest = sorted(versions.keys())[-1]
    deses = versions[latest]
    return clog['baseline'], latest, deses


with tempfile.TemporaryDirectory() as tmpdir:
    base, latest, deses = load_changelog()
    version = base+'-'+latest
    build_dir = os.path.join(tmpdir, 'openubmc-qemu-'+base)
    shutil.copytree('deb_build/', build_dir)
    subprocess.run(['sh', 'build_qemu.sh'], check=True)
    bin_dir = os.path.join(build_dir, 'usr/share/qemu/bin/')
    os.makedirs(bin_dir, exist_ok=True)
    shutil.copy('build/qemu-system-aarch64', bin_dir)
    version_file = os.path.join(bin_dir, 'openUBMC_version')
    with open(version_file, "w", encoding="utf-8") as f:
        f.write(version)
    os.chdir(build_dir)
    os.environ["DEBFULLNAME"] = 'openUBMC'
    os.environ["DEBEMAIL"] = 'cicd@public.openubmc.cn'
    pypi_version = latest.split('build')[0]+'.0'
    os.environ["qemu_pypi_version"] = pypi_version
    subprocess.run([
        'dch', '--create',
        '--package', 'openubmc-qemu',
        '--newversion', version,
        '--distribution', 'unstable',
        '--urgency', 'low',
        deses[0]
    ], check=True)
    for des in deses[1:]:
        subprocess.run([
            'dch', '--append',
            des
        ], check=True)
    subprocess.run(['dpkg-buildpackage', '-us', '-uc'], check=True)
    subprocess.run(['ls', '-al', tmpdir], check=True)
    shutil.rmtree(build_dir)
    shutil.copytree(tmpdir, os.path.join(cwd, 'output'), dirs_exist_ok=True)
